package com.freejava.myblog.services;

import com.freejava.myblog.pojo.MyArticle;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {

    @Autowired
    MongoTemplate mongoTemplate;

    private final String tableName = "my_article";

    // 创建文章
    public boolean add(MyArticle myArticle) {
        long unixTime = System.currentTimeMillis() / 1000L;
        int nowUnixTime = (int) unixTime;
        myArticle.setCreated(nowUnixTime);
//        Object obj = mongoTemplate.save(myArticle, this.tableName);
        MyArticle obj = mongoTemplate.save(myArticle);
        if (obj != null) {
            return true;
        } else {
            return false;
        }
    }

    // 获取文章列表 不分页
    public List<MyArticle> findAll() {
        return mongoTemplate.findAll(MyArticle.class);
    }

    // 获取文章列表 分页, 一页是2条数据
    public List<MyArticle> getListByPageNum(int pageNum) {
        Query query = new Query();
        query.skip((pageNum - 1) * 2);
        query.limit(2);
        return mongoTemplate.find(query, MyArticle.class);
    }

    // 文章详情
    public MyArticle detail(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, MyArticle.class);
    }

    // 修改文章
    public boolean update(MyArticle myArticle) {
        Query query = Query.query(Criteria.where("id").is(myArticle.getId()));
        Update update = new Update();
        update.set("title", myArticle.getTitle());
        update.set("author", myArticle.getAuthor());
        update.set("category_id", myArticle.getCategoryId());
        update.set("id", myArticle.getId());
        update.set("content", myArticle.getContent());
        update.set("is_deleted", myArticle.getIs_deleted());
        long unixTime = System.currentTimeMillis() / 1000L;
        int nowUnixTime = (int) unixTime;
        update.set("modified", nowUnixTime);

        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, MyArticle.class);
        if (updateResult.getModifiedCount() > 0) {
            return true;
        } else {
            return false;
        }
    }


    // 删除
    public boolean delete(String id) {
        // return myArticleMapper.delete(id);
        MyArticle myArticle = new MyArticle();
        myArticle.setId(id);
        DeleteResult deleteResult = mongoTemplate.remove(myArticle);
        if (deleteResult.getDeletedCount() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
